module.exports = ( function() {

    let MianThread;

    let IsRun = false;
    let IsPause = false;

    let PauseFun = "while( true ){ if ( !IsPause ) { break; sleep(100); } }";
    
    this.SetRunState = function( state ) {
        IsRun = state;
    }
    this.GetRunState = function() {
        return IsRun;
    }
    this.SetPauseState = function( state ) {
        IsPause = state;
    }
    this.GetPauseState = function () {
        return IsPause;
    }
    /**
     * 保证功能不会被重复运行.
     * @param {*} main 要执行的功能函数
     * @returns void
     */
    this.RunScript = ( main ) => {
        try {
            if ( this.GetRunState() ) {
                toastLog( "该功能正在运行,无法重复运行" );
                return;
            }
            let mainStr = main.toString();
            let mainStrArry = mainStr.split( "\n" );
            let mainFunStr = "";
            for ( let i in mainStrArry ) {
                if ( mainStrArry[ i ] == "" ) continue;
                if ( i <= mainStrArry.length - 3 ) {
                    mainFunStr += mainStrArry[ i ] + "\n" + PauseFun + "\n";
                }
            }
            mainFunStr += "}";
            main = eval( mainFunStr );
            // log(main.toString());
            this.SetRunState( true );
            MianThread = threads.start( main );
        } catch ( e ) {
            toastLog( "[ CATCH_INFO ]: " + e );
            this.SetRunState( false );
            return;
        }
        //等待运行脚本的线程执行完成,改变状态
        threads.start( () => {
            if ( MianThread ) {
                MianThread.join();
                this.SetRunState( false );
            }
        } );
    }
    this.Stop = function() {
        if ( this.GetRunState() ) {
            MianThread.interrupt();
        }
    }
    this.Pause = function() {
        if ( !this.GetPauseState() ) {
            this.SetPauseState( true );
            console.log("当前逻辑已暂停!");
        } else {
            console.log( "继续执行代码逻辑" );
            this.SetPauseState( false );
        }
    }

    return this;
} )()